#include <func.h>

#define N 10000000
typedef struct{
    int num;
    pthread_mutex_t mutex;
}data_t;

int main()
{
    //共享内存的创建和连接
    int shmid;
    shmid=shmget(1000,4096,IPC_CREAT|0600);
    ERROR_CHECK(shmid,-1,"shmget");
    printf("shmid=%d\n",shmid);
    data_t *p=shmat(shmid,NULL,0);
    ERROR_CHECK(p,(data_t*)-1,"shmat")
    int i;
    p->num=0;
    pthread_mutexattr_t mutex_attr;//定义一个锁属性
    pthread_mutexattr_init(&mutex_attr);//初始化锁属性
    pthread_mutexattr_setpshared(&mutex_attr,PTHREAD_PROCESS_SHARED);//设置为可在进程间使用的
    pthread_mutex_init(&p->mutex,&mutex_attr);
    if(!fork())
    {
        for(i=0;i<N;i++)
        {
            pthread_mutex_lock(&p->mutex);
            p->num+=1;
            pthread_mutex_unlock(&p->mutex);
        }
        return 0;
    }else{
        for(i=0;i<N;i++)
        {
            pthread_mutex_lock(&p->mutex);
            p->num+=1;
            pthread_mutex_unlock(&p->mutex);
        }
        wait(NULL);
        printf("p->num=%d\n",p->num);
        return 0;
    }
}